package com.bbs.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bbs.resp.ResultMsg;
import com.bbs.service.TestService;
import com.bbs.service.impl.TestServiceImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * @author: ZackYoung
 * @time: 2020/11/9
 */
@RestController
public class TestController {
    @Resource
    TestService testService;

    @RequestMapping("/echo/{string}")
    @SentinelResource(value = "print", blockHandler = "defeated", fallbackClass = TestServiceImpl.class)
    public String print(@PathVariable String string) {
        return testService.echo(string);
    }

    public String defeated(@PathVariable String string) {
        return "你被限流啦！";
    }

    @Value("${server.port}")
    String port;

    @Resource
    RestTemplate restTemplate;

    @RequestMapping("/article/details/{id}")
    public ResultMsg text(@PathVariable String id) {
        String forObject = restTemplate.getForObject("http://172.16.1.2:9200/articles/_search?q=" + id, String.class);
        JSONObject jsonObject = JSON.parseObject(forObject);
        Object hits = jsonObject.getObject("hits", Object.class);
        ResultMsg resultMsg = new ResultMsg();
        resultMsg.setMsg(port);
        resultMsg.setData(hits);
        return resultMsg;
    }
}
